package cn.tannn.ops.util;

import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.ops.nginx.entity.Domains;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

/**
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @version V1.0
 * @date 2024/8/22 下午3:25
 */
public class NginxUtil {
    private static final Logger LOG = LoggerFactory.getLogger(NginxUtil.class);

    /**
     * 域名校验
     * @param domain 域名
     * @return Domains
     * @throws NoSuchAlgorithmException NoSuchAlgorithmException
     * @throws KeyManagementException KeyManagementException
     * @throws IOException IOException
     */
    public static @NotNull Domains domainSslInfo(String domain) throws NoSuchAlgorithmException, KeyManagementException, IOException {
        // 忽略SSL证书验证
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }
                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
        };

        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // 忽略主机名验证
        HostnameVerifier allHostsValid = (hostname, session) -> true;
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);


        Domains domains = new Domains();
        URL url;
        if(domain.startsWith("https://")){
            url = new URL(domain);
        }else {
            url = new URL("https://"+ domain);
        }
        domains.setDomain(url.getHost());

       try {
           HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
           connection.connect();
           Certificate[] certificates = connection.getServerCertificates();
           if(certificates != null && certificates.length > 0){
               if (certificates[0] instanceof X509Certificate certificate) {
                   //第一个就是服务器本身证书，后续的是证书链上的其他证书
                   domains.setSubject(certificate. getIssuerX500Principal().getName());
                   domains.setIssuer(certificate. getIssuerX500Principal().getName());
                   domains.setExpiryAfter(certificate.getNotBefore());
                   domains.setExpiryAfter(certificate.getNotAfter());
               } else {
                  LOG.warn("Not an X509Certificate" );
               }
           }
           connection.disconnect();
       }catch (UnknownHostException unknownHostException){
           throw new BusinessException("请输入正确的域名地址");
       }catch (Exception e){
           throw e;
       }
        return domains;
    }
}
